<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🎮 游戏集合中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei UI', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            color: #2c3e50;
            line-height: 1.6;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        /* 头部区域 */
        .header {
            text-align: center;
            margin-bottom: 40px;
            padding: 30px 0;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .header h1 {
            font-size: 3rem;
            color: #007bff;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.2rem;
            color: #6c757d;
            font-weight: 300;
        }

        /* 工具栏 */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            flex-wrap: wrap;
            gap: 15px;
        }

        .toolbar-left, .toolbar-right {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        /* 分类标题 */
        .category-header {
            margin: 40px 0 20px 0;
            padding-left: 10px;
            border-left: 4px solid #007bff;
        }

        .category-title {
            font-size: 1.8rem;
            color: #007bff;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .category-desc {
            color: #6c757d;
            font-size: 1rem;
        }

        /* 游戏网格 */
        .games-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        /* 游戏卡片 */
        .game-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            transition: all 0.3s ease;
            position: relative;
        }

        .game-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
        }

        .game-image {
            width: 100%;
            height: 200px;
            background: linear-gradient(45deg, #f8f9fa, #e9ecef);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 4rem;
            color: #007bff;
            position: relative;
            overflow: hidden;
        }

        .game-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .status-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            color: white;
        }

        .status-available { background: #28a745; }
        .status-coming_soon { background: #ffc107; color: #212529; }
        .status-maintenance { background: #dc3545; }

        .game-info {
            padding: 20px;
        }

        .game-title {
            font-size: 1.4rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .game-description {
            color: #6c757d;
            font-size: 0.95rem;
            margin-bottom: 15px;
            line-height: 1.5;
        }

        .game-stats {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 10px 0;
            border-top: 1px solid #e9ecef;
        }

        .rating {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #ffc107;
            font-weight: 600;
        }

        .play-count {
            color: #6c757d;
            font-size: 0.9rem;
        }

        .game-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 13px;
            flex: 1;
            min-width: 80px;
            justify-content: center;
        }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            backdrop-filter: blur(5px);
        }

        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            border-radius: 15px;
            padding: 30px;
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.3s ease;
        }

        @keyframes modalSlideIn {
            from {
                transform: scale(0.8) translateY(-50px);
                opacity: 0;
            }
            to {
                transform: scale(1) translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e9ecef;
        }

        .modal-title {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2c3e50;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #6c757d;
            padding: 5px;
            border-radius: 50%;
            transition: all 0.3s ease;
        }

        .close-btn:hover {
            background: #f8f9fa;
            color: #dc3545;
        }

        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #2c3e50;
        }

        .form-control {
            width: 100%;
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        /* 统计页面 */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }

            .header h1 {
                font-size: 2rem;
            }

            .toolbar {
                flex-direction: column;
                align-items: stretch;
            }

            .toolbar-left, .toolbar-right {
                justify-content: center;
            }

            .games-grid {
                grid-template-columns: 1fr;
            }

            .game-actions {
                flex-direction: column;
            }

            .btn-sm {
                flex: none;
            }
        }

        /* 动画效果 */
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes pulse {
            0% { 
                transform: scale(1); 
                color: #6c757d; 
            }
            50% { 
                transform: scale(1.1); 
                color: #28a745; 
                font-weight: bold;
            }
            100% { 
                transform: scale(1); 
                color: #6c757d; 
            }
        }

        @keyframes newCardHighlight {
            0% { 
                transform: scale(0.8);
                opacity: 0;
                box-shadow: 0 0 20px rgba(40, 167, 69, 0.6);
            }
            50% { 
                transform: scale(1.05);
                opacity: 1;
                box-shadow: 0 0 30px rgba(40, 167, 69, 0.8);
            }
            100% { 
                transform: scale(1);
                opacity: 1;
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            }
        }

        /* 搜索栏 */
        .search-container {
            position: relative;
            flex-grow: 1;
            max-width: 300px;
        }

        .search-input {
            width: 100%;
            padding: 12px 20px 12px 45px;
            border: 2px solid #e9ecef;
            border-radius: 25px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        .search-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部区域 -->
        <div class="header fade-in">
            <h1>🎮 游戏集合中心</h1>
            <p>发现并享受精彩游戏</p>
        </div>

        <!-- 工具栏 -->
        <div class="toolbar fade-in">
            <div class="toolbar-left">
                <button class="btn btn-success" onclick="showAddGameModal()">
                    ➕ 添加游戏
                </button>
                <button class="btn btn-primary" onclick="refreshGamesList()">
                    🔄 刷新列表
                </button>
                <button class="btn btn-secondary" onclick="showStatsModal()">
                    📊 游戏统计
                </button>
            </div>
            <div class="toolbar-right">
                <div class="search-container">
                    <span class="search-icon">🔍</span>
                    <input type="text" class="search-input" placeholder="搜索游戏..." id="searchInput" oninput="filterGames()">
                </div>
            </div>
        </div>

        <!-- 游戏列表容器 -->
        <div id="gamesContainer"></div>
    </div>

    <!-- 游戏详情模态框 -->
    <div class="modal" id="gameDetailModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="detailTitle">游戏详情</h2>
                <button class="close-btn" onclick="closeModal('gameDetailModal')">&times;</button>
            </div>
            <div id="detailContent"></div>
        </div>
    </div>

    <!-- 游戏配置模态框 -->
    <div class="modal" id="gameConfigModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" id="configTitle">游戏配置</h2>
                <button class="close-btn" onclick="closeModal('gameConfigModal')">&times;</button>
            </div>
            <div id="configContent"></div>
        </div>
    </div>

    <!-- 添加游戏模态框 -->
    <div class="modal" id="addGameModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">添加新游戏</h2>
                <button class="close-btn" onclick="closeModal('addGameModal')">&times;</button>
            </div>
            <form id="addGameForm">
                <div class="form-group">
                    <label class="form-label">游戏名称</label>
                    <input type="text" class="form-control" id="gameName" required>
                </div>
                <div class="form-group">
                    <label class="form-label">游戏描述</label>
                    <textarea class="form-control" id="gameDescription" rows="3" required></textarea>
                </div>
                <div class="form-group">
                    <label class="form-label">游戏文件路径</label>
                    <input type="text" class="form-control" id="gamePath" required>
                </div>
                <div class="form-group">
                    <label class="form-label">游戏图片路径</label>
                    <input type="text" class="form-control" id="gameImage">
                </div>
                <div class="form-group">
                    <label class="form-label">游戏类别</label>
                    <select class="form-control" id="gameCategory">
                        <option value="益智">益智</option>
                        <option value="动作">动作</option>
                        <option value="冒险">冒险</option>
                        <option value="策略">策略</option>
                        <option value="射击">射击</option>
                        <option value="休闲">休闲</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">初始评分 (0-5)</label>
                    <input type="number" class="form-control" id="gameRating" min="0" max="5" step="0.1" value="4.0">
                </div>
                <div style="display: flex; gap: 10px; margin-top: 30px;">
                    <button type="submit" class="btn btn-success" style="flex: 1;">保存游戏</button>
                    <button type="button" class="btn btn-secondary" onclick="closeModal('addGameModal')" style="flex: 1;">取消</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 统计模态框 -->
    <div class="modal" id="statsModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">游戏统计</h2>
                <button class="close-btn" onclick="closeModal('statsModal')">&times;</button>
            </div>
            <div id="statsContent"></div>
        </div>
    </div>

    <script>
        // 游戏数据 (从服务器获取)
        let gamesData = [];
        
        // API基础URL
        const API_BASE = '/api';

        // 游戏图标映射
        const gameIcons = {
            'tetris': '🧩',
            'snake': '🐍',
            'tank_battle': '🎖️',
            'push_box': '📦',
            'star_collector': '⭐',
            'lane_conflict': '⚔️',
            'sandbox_war': '🏰',
            'game_2048': '🔢',
            'default': '🎮'
        };

        // 状态文本映射
        const statusText = {
            'available': '可用',
            'coming_soon': '即将推出',
            'maintenance': '维护中'
        };

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            refreshGamesList();
        });

        // 刷新游戏列表
        async function refreshGamesList() {
            const container = document.getElementById('gamesContainer');
            container.innerHTML = '<div style="text-align: center; padding: 50px;">🔄 加载中...</div>';

            try {
                const response = await fetch(`${API_BASE}/games`);
                if (!response.ok) {
                    throw new Error('获取游戏列表失败');
                }
                
                gamesData = await response.json();
                
                container.innerHTML = '';

                // 按类别分组
                const categories = {};
                gamesData.forEach(game => {
                    const category = game.category;
                    if (!categories[category]) {
                        categories[category] = [];
                    }
                    categories[category].push(game);
                });

                // 渲染每个类别
                Object.keys(categories).forEach(category => {
                    const games = categories[category];
                    
                    // 创建类别标题
                    const categoryHeader = document.createElement('div');
                    categoryHeader.className = 'category-header fade-in';
                    categoryHeader.innerHTML = `
                        <div class="category-title">📁 ${category}</div>
                        <div class="category-desc">${games.length} 个游戏</div>
                    `;
                    container.appendChild(categoryHeader);

                    // 创建游戏网格
                    const gamesGrid = document.createElement('div');
                    gamesGrid.className = 'games-grid fade-in';

                    games.forEach(game => {
                        const gameCard = createGameCard(game);
                        gamesGrid.appendChild(gameCard);
                    });

                    container.appendChild(gamesGrid);
                });
            } catch (error) {
                container.innerHTML = `
                    <div style="text-align: center; padding: 50px; color: #dc3545;">
                        ❌ 获取游戏列表失败: ${error.message}<br>
                        <button class="btn btn-primary" onclick="refreshGamesList()" style="margin-top: 20px;">重试</button>
                    </div>
                `;
            }
        }

        // 创建游戏卡片
        function createGameCard(game) {
            const card = document.createElement('div');
            card.className = 'game-card';
            card.setAttribute('data-game-id', game.id);
            card.setAttribute('data-category', game.category);
            card.setAttribute('data-name', game.name.toLowerCase());

            const icon = gameIcons[game.id] || gameIcons['default'];
            const lastPlayed = game.last_played ? 
                new Date(game.last_played).toLocaleDateString('zh-CN') : '从未游玩';

            card.innerHTML = `
                <div class="game-image">
                    ${game.image ? `<img src="${game.image}" alt="${game.name}" onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">` : ''}
                    <span style="${game.image ? 'display:none' : ''}">${icon}</span>
                    <div class="status-badge status-${game.status}">
                        ${statusText[game.status] || '未知'}
                    </div>
                </div>
                <div class="game-info">
                    <div class="game-title">${game.name}</div>
                    <div class="game-description">${game.description}</div>
                    <div class="game-stats">
                        <div class="rating">
                            <span>⭐</span>
                            <span>${game.rating}</span>
                        </div>
                        <div class="play-count">🎮 ${game.play_count}</div>
                    </div>
                    <div class="game-actions">
                        ${game.status === 'available' ? 
                            `<button type="button" class="btn btn-success btn-sm" onclick="event.preventDefault(); startGame('${game.id}'); return false;">▶ 开始游戏</button>` :
                            `<button type="button" class="btn btn-secondary btn-sm" disabled>⚠ 暂不可用</button>`
                        }
                        <button type="button" class="btn btn-secondary btn-sm" onclick="event.preventDefault(); showConfigModal('${game.id}'); return false;">⚙ 配置</button>
                        <button type="button" class="btn btn-primary btn-sm" onclick="event.preventDefault(); showDetailModal('${game.id}'); return false;">📋 详情</button>
                    </div>
                </div>
            `;

            return card;
        }

        // 启动游戏
        async function startGame(gameId) {
            // 防止默认行为和事件冒泡
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            
            const game = gamesData.find(g => g.id === gameId);
            if (!game) {
                showNotification('游戏不存在', 'error');
                return false;
            }

            try {
                const response = await fetch(`${API_BASE}/games/${gameId}/start`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    showNotification(result.message, 'success');
                    
                    // 更新本地数据
                    game.play_count = result.play_count;
                    game.last_played = new Date().toISOString();
                    
                    // 只更新当前游戏卡片的统计数据，不刷新整个页面
                    updateGameCardStats(gameId, result.play_count);
                } else {
                    showNotification(result.error || '启动游戏失败', 'error');
                }
            } catch (error) {
                console.error('启动游戏出错:', error);
                showNotification(`启动游戏失败: ${error.message}`, 'error');
            }
            
            return false; // 确保不触发任何默认行为
        }

        // 更新游戏卡片统计数据
        function updateGameCardStats(gameId, playCount) {
            // 更新游戏卡片中的统计
            const gameCard = document.querySelector(`[data-game-id="${gameId}"]`);
            if (gameCard) {
                const playCountElement = gameCard.querySelector('.play-count');
                if (playCountElement) {
                    playCountElement.textContent = `🎮 ${playCount}`;
                    
                    // 添加更新动画效果
                    playCountElement.style.animation = 'pulse 0.5s ease-in-out';
                    setTimeout(() => {
                        playCountElement.style.animation = '';
                    }, 500);
                }
            }

            // 如果详情模态框是打开的，也更新其中的统计信息
            const detailModal = document.getElementById('gameDetailModal');
            if (detailModal.classList.contains('show')) {
                const detailContent = document.getElementById('detailContent');
                if (detailContent) {
                    // 更新详情页面中的游玩次数显示
                    const detailText = detailContent.innerHTML;
                    const updatedText = detailText.replace(
                        /🎯 游玩次数: \d+/, 
                        `🎯 游玩次数: ${playCount}`
                    ).replace(
                        /📅 最后游玩: [^<\n]+/, 
                        `📅 最后游玩: ${new Date().toLocaleString('zh-CN')}`
                    );
                    detailContent.innerHTML = updatedText;
                    
                    // 添加视觉反馈
                    const gameCountRegex = /🎯 游玩次数: \d+/;
                    if (gameCountRegex.test(detailContent.innerHTML)) {
                        detailContent.style.animation = 'fadeIn 0.3s ease-in-out';
                        setTimeout(() => {
                            detailContent.style.animation = '';
                        }, 300);
                    }
                }
            }
        }

        // 从详情页面启动游戏
        async function startGameFromDetail(gameId) {
            // 防止默认行为和事件冒泡
            if (event) {
                event.preventDefault();
                event.stopPropagation();
            }
            
            try {
                await startGame(gameId);
                // 游戏启动成功后关闭详情模态框
                closeModal('gameDetailModal');
            } catch (error) {
                // 如果启动失败，不关闭模态框，让用户看到错误信息
                console.error('从详情页面启动游戏失败:', error);
            }
            
            return false; // 确保不触发任何默认行为
        }

        // 动态添加游戏卡片
        function addGameCardDynamically(game) {
            const container = document.getElementById('gamesContainer');
            
            // 查找对应类别的游戏网格
            let targetGrid = null;
            let categoryExists = false;
            
            // 遍历所有类别标题，查找匹配的类别
            const categoryHeaders = container.querySelectorAll('.category-header');
            categoryHeaders.forEach(header => {
                const titleElement = header.querySelector('.category-title');
                if (titleElement && titleElement.textContent.includes(game.category)) {
                    categoryExists = true;
                    // 找到类别标题后的游戏网格
                    targetGrid = header.nextElementSibling;
                    
                    // 更新类别下的游戏数量
                    const descElement = header.querySelector('.category-desc');
                    if (descElement) {
                        const currentCount = parseInt(descElement.textContent.match(/\d+/)[0]);
                        descElement.textContent = `${currentCount + 1} 个游戏`;
                    }
                }
            });
            
            // 如果类别不存在，创建新的类别
            if (!categoryExists) {
                // 创建类别标题
                const categoryHeader = document.createElement('div');
                categoryHeader.className = 'category-header fade-in';
                categoryHeader.innerHTML = `
                    <div class="category-title">📁 ${game.category}</div>
                    <div class="category-desc">1 个游戏</div>
                `;
                
                // 创建游戏网格
                targetGrid = document.createElement('div');
                targetGrid.className = 'games-grid fade-in';
                
                // 添加到容器
                container.appendChild(categoryHeader);
                container.appendChild(targetGrid);
            }
            
            // 创建并添加游戏卡片
            if (targetGrid) {
                const gameCard = createGameCard(game);
                targetGrid.appendChild(gameCard);
                
                // 添加一个特殊的闪烁效果来突出新添加的卡片
                gameCard.style.animation = 'newCardHighlight 1s ease-in-out';
                setTimeout(() => {
                    gameCard.style.animation = '';
                }, 1000);
            }
        }

        // 显示游戏详情
        function showDetailModal(gameId) {
            const game = gamesData.find(g => g.id === gameId);
            if (!game) return;

            const modal = document.getElementById('gameDetailModal');
            const title = document.getElementById('detailTitle');
            const content = document.getElementById('detailContent');

            title.textContent = `详情 - ${game.name}`;

            const lastPlayed = game.last_played ? 
                new Date(game.last_played).toLocaleString('zh-CN') : '从未游玩';

            let settingsHtml = '';
            Object.keys(game.settings).forEach(key => {
                const value = game.settings[key];
                const displayValue = typeof value === 'boolean' ? 
                    (value ? '✅ 是' : '❌ 否') : value;
                settingsHtml += `<div>• ${key.replace('_', ' ')}: ${displayValue}</div>`;
            });

            content.innerHTML = `
                <div style="margin-bottom: 20px;">
                    <div style="font-size: 4rem; text-align: center; margin-bottom: 15px;">
                        ${gameIcons[game.id] || gameIcons['default']}
                    </div>
                </div>
                <div style="line-height: 1.8;">
                    <p><strong>🎮 游戏名称:</strong> ${game.name}</p>
                    <p><strong>📂 类别:</strong> ${game.category}</p>
                    <p><strong>⭐ 评分:</strong> ${game.rating}/5.0</p>
                    <p><strong>🎯 游玩次数:</strong> ${game.play_count}</p>
                    <p><strong>📅 最后游玩:</strong> ${lastPlayed}</p>
                    <p><strong>📁 文件路径:</strong> ${game.path}</p>
                    <p><strong>🔧 状态:</strong> ${statusText[game.status] || '未知'}</p>
                    <p><strong>📖 游戏描述:</strong></p>
                    <p style="margin-left: 20px; color: #6c757d;">${game.description}</p>
                    <p><strong>⚙️ 当前设置:</strong></p>
                    <div style="margin-left: 20px; color: #6c757d;">
                        ${settingsHtml}
                    </div>
                </div>
                ${game.status === 'available' ? 
                    `<div style="margin-top: 30px;">
                        <button type="button" class="btn btn-success" onclick="event.preventDefault(); startGameFromDetail('${game.id}'); return false;">
                            ▶ 开始游戏
                        </button>
                    </div>` : ''
                }
            `;

            modal.classList.add('show');
        }

        // 显示游戏配置
        function showConfigModal(gameId) {
            const game = gamesData.find(g => g.id === gameId);
            if (!game) return;

            const modal = document.getElementById('gameConfigModal');
            const title = document.getElementById('configTitle');
            const content = document.getElementById('configContent');

            title.textContent = `配置 - ${game.name}`;

            let formHtml = '<form id="configForm">';
            Object.keys(game.settings).forEach(key => {
                const value = game.settings[key];
                const label = key.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
                
                if (typeof value === 'boolean') {
                    formHtml += `
                        <div class="form-group">
                            <label class="form-label">
                                <input type="checkbox" ${value ? 'checked' : ''} 
                                       onchange="updateGameSetting('${gameId}', '${key}', this.checked)">
                                ${label}
                            </label>
                        </div>
                    `;
                } else {
                    formHtml += `
                        <div class="form-group">
                            <label class="form-label">${label}</label>
                            <input type="text" class="form-control" value="${value}"
                                   onchange="updateGameSetting('${gameId}', '${key}', this.value)">
                        </div>
                    `;
                }
            });
            formHtml += '</form>';

            content.innerHTML = formHtml + `
                <div style="margin-top: 30px; display: flex; gap: 10px;">
                    <button class="btn btn-success" onclick="closeModal('gameConfigModal')">保存设置</button>
                    <button class="btn btn-secondary" onclick="closeModal('gameConfigModal')">取消</button>
                </div>
            `;

            modal.classList.add('show');
        }

        // 更新游戏设置
        async function updateGameSetting(gameId, key, value) {
            const game = gamesData.find(g => g.id === gameId);
            if (!game) return;

            // 先更新本地数据
            game.settings[key] = value;

            try {
                const response = await fetch(`${API_BASE}/games/${gameId}/settings`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ [key]: value })
                });

                const result = await response.json();
                
                if (!response.ok || !result.success) {
                    // 如果保存失败，显示错误消息（但不回滚本地更改，因为用户可能还在编辑）
                    console.error('保存设置失败:', result.error);
                }
            } catch (error) {
                console.error('保存设置失败:', error);
            }
        }

        // 显示添加游戏模态框
        function showAddGameModal() {
            const modal = document.getElementById('addGameModal');
            document.getElementById('addGameForm').reset();
            modal.classList.add('show');
        }

        // 处理添加游戏表单
        document.getElementById('addGameForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const name = document.getElementById('gameName').value.trim();
            const description = document.getElementById('gameDescription').value.trim();
            const path = document.getElementById('gamePath').value.trim();
            const image = document.getElementById('gameImage').value.trim();
            const category = document.getElementById('gameCategory').value;
            const rating = parseFloat(document.getElementById('gameRating').value);

            if (!name || !description || !path) {
                showNotification('请填写所有必需字段！', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/games`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: name,
                        description: description,
                        path: path,
                        category: category,
                        rating: rating,
                        image: image
                    })
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    // 添加新游戏到本地数据
                    gamesData.push(result.game);
                    
                    // 动态添加游戏卡片而不是刷新整个页面
                    addGameCardDynamically(result.game);
                    
                    closeModal('addGameModal');
                    showNotification(result.message, 'success');
                } else {
                    showNotification(result.error || '添加游戏失败', 'error');
                }
            } catch (error) {
                showNotification(`添加游戏失败: ${error.message}`, 'error');
            }
        });

        // 显示统计模态框
        async function showStatsModal() {
            const modal = document.getElementById('statsModal');
            const content = document.getElementById('statsContent');
            
            content.innerHTML = '<div style="text-align: center; padding: 50px;">🔄 加载统计数据...</div>';
            modal.classList.add('show');

            try {
                const response = await fetch(`${API_BASE}/stats`);
                if (!response.ok) {
                    throw new Error('获取统计数据失败');
                }
                
                const stats = await response.json();

                content.innerHTML = `
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-number">${stats.total_games}</div>
                            <div class="stat-label">总游戏数</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${stats.available_games}</div>
                            <div class="stat-label">可用游戏</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${stats.total_plays}</div>
                            <div class="stat-label">总游玩次数</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-number">${stats.most_played ? stats.most_played.play_count : 0}</div>
                            <div class="stat-label">最高游玩次数</div>
                        </div>
                    </div>
                    <div style="margin-top: 20px; padding: 20px; background: #f8f9fa; border-radius: 10px;">
                        <h3 style="margin-bottom: 15px;">📈 最受欢迎游戏</h3>
                        ${stats.most_played && stats.most_played.play_count > 0 ? 
                            `<p><strong>${stats.most_played.name}</strong> - ${stats.most_played.play_count} 次游玩</p>` :
                            `<p>暂无游玩记录</p>`
                        }
                        <p style="color: #6c757d; margin-top: 10px;">统计时间: ${new Date().toLocaleString('zh-CN')}</p>
                    </div>
                    <div style="margin-top: 20px;">
                        <button class="btn btn-primary" onclick="closeModal('statsModal')">关闭</button>
                    </div>
                `;
            } catch (error) {
                content.innerHTML = `
                    <div style="text-align: center; padding: 50px; color: #dc3545;">
                        ❌ 获取统计数据失败: ${error.message}<br>
                        <button class="btn btn-primary" onclick="showStatsModal()" style="margin-top: 20px;">重试</button>
                    </div>
                `;
            }
        }

        // 搜索过滤功能
        function filterGames() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const gameCards = document.querySelectorAll('.game-card');

            gameCards.forEach(card => {
                const gameName = card.getAttribute('data-name');
                const category = card.getAttribute('data-category');
                
                if (gameName.includes(searchTerm) || category.includes(searchTerm)) {
                    card.style.display = 'block';
                } else {
                    card.style.display = 'none';
                }
            });
        }

        // 关闭模态框
        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
            modal.classList.remove('show');
        }

        // 点击模态框外部关闭
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('modal')) {
                e.target.classList.remove('show');
            }
        });

        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const openModals = document.querySelectorAll('.modal.show');
                openModals.forEach(modal => modal.classList.remove('show'));
            }
        });

        // 显示通知
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 15px 20px;
                background: ${type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : '#007bff'};
                color: white;
                border-radius: 8px;
                box-shadow: 0 5px 15px rgba(0,0,0,0.3);
                z-index: 2000;
                font-weight: 600;
                animation: slideInRight 0.3s ease;
            `;
            notification.textContent = message;

            document.body.appendChild(notification);

            setTimeout(() => {
                notification.style.animation = 'slideOutRight 0.3s ease forwards';
                setTimeout(() => document.body.removeChild(notification), 300);
            }, 3000);
        }

        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideInRight {
                from { transform: translateX(100%); }
                to { transform: translateX(0); }
            }
            @keyframes slideOutRight {
                from { transform: translateX(0); }
                to { transform: translateX(100%); }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html> 